import Vue from "vue";
import VueAxios from "vue-axios";
import axios from "axios";
import ElementUI from "element-ui";


Vue.use(VueAxios, axios);

axios.defaults.baseURL = 'http://127.0.0.1:8000/'
//设置axios请求头加入token  //request 拦截器
axios.interceptors.request.use(config => {
        if (config.push === '/' || config.push === '/login') {
        } else {
            if (localStorage.getItem('token')) {
                //在请求头加入token，名字要和后端接收请求头的token名字一样
                config.headers.token = localStorage.getItem('token');
            }
        }
        return config;
    },
    error => {
        return Promise.reject(error);
    });

//响应token过期 拦截器
axios.interceptors.response.use(response => {
        //和后端约定的返回码
        if (response.data.code == 401) {
            // 引用elementui message提示框
            ElementUI.Message({
                dangerouslyUseHTMLString: true,
                message: '<div><p>身份已失效！</p><p><i class="el-icon-loading"></i>正在前往登录页面...</p></div>',
                type: 'warning'
            });
            //清除token
            localStorage.removeItem('token');
            localStorage.removeItem('username');
            localStorage.removeItem('nickname');
            //跳转
            setTimeout(function () {
                window.location.href = '/login'
            }, 2000)
        } else if (response.data.code == 402) {
            ElementUI.Message({
                dangerouslyUseHTMLString: true,
                message: '<div><p>未登录或身份已失效！</p><p><i class="el-icon-loading"></i>正在前往登录页面...</p></div>',
                type: 'warning'
            });
            //跳转
            setTimeout(function () {
                window.location.href = '/login'
            }, 2000)
        } else if (response.data.code == 403) {
            window.location.href = '/tips'
        } else {
            return response
        }
    },
    error => {
        return Promise.reject(error);
    })

export default axios